package org.linlinjava.litemall.db.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.beetl.sql.core.query.LambdaQuery;
import org.linlinjava.litemall.db.BeetlParams;
import org.linlinjava.litemall.db.domain.LitemallAftersale;
import org.linlinjava.litemall.db.mapper.LitemallAftersaleDao;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class LitemallAftersaleService {
    @Resource
    private LitemallAftersaleDao aftersaleDao;

    public LitemallAftersale findById(Integer id) {
        return aftersaleDao.single(id);
    }

    public LitemallAftersale findById(Integer userId, Integer id) {
    	
    	LitemallAftersale sale = new LitemallAftersale();
    	sale.setUserId(userId);
    	sale.setId(id);
    	sale.setDeleted(false);
    	return aftersaleDao.templateOne(sale);
		/*
		 * LitemallAftersaleExample example = new LitemallAftersaleExample();
		 * example.or().andIdEqualTo(id).andUserIdEqualTo(userId).andDeletedEqualTo(
		 * false); return aftersaleMapper.selectOneByExample(example);
		 */
    }

    public List<LitemallAftersale> queryList(Integer userId, Short status, Integer page, Integer limit, String sort, String order) {
    	
    	LambdaQuery<LitemallAftersale> query = aftersaleDao.createLambdaQuery();
    	if (status != null) {
    		query.andEq(LitemallAftersale::getStatus , status);
        }
    	query.andEq(LitemallAftersale:: getDeleted, false);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
        	query.orderBy(sort + " " + order);
        }
        else{
        	query.orderBy(LitemallAftersale.Column.addTime.desc());
        }
        query.limit(page, limit);
        
        List<LitemallAftersale> list = query.select();
        return list;
		/*
		 * LitemallAftersaleExample example = new LitemallAftersaleExample();
		 * LitemallAftersaleExample.Criteria criteria = example.or();
		 * criteria.andUserIdEqualTo(userId); if (status != null) {
		 * criteria.andStatusEqualTo(status); } criteria.andDeletedEqualTo(false); if
		 * (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
		 * example.setOrderByClause(sort + " " + order); } else{
		 * example.setOrderByClause(LitemallAftersale.Column.addTime.desc()); }
		 * 
		 * PageHelper.startPage(page, limit); return
		 * aftersaleMapper.selectByExample(example);
		 */
    }

    public List<LitemallAftersale> querySelective(Integer orderId, String aftersaleSn, Short status, Integer page, Integer limit, String sort, String order) {
    	
    	LambdaQuery<LitemallAftersale> query = aftersaleDao.createLambdaQuery();
    	 if (orderId != null) {
    		 query.andEq(LitemallAftersale::getOrderId , orderId);
         }
         if (!StringUtils.isEmpty(aftersaleSn)) {
        	 query.andEq(LitemallAftersale::getAftersaleSn , aftersaleSn);
         }
         if (status != null) {
        	 query.andEq(LitemallAftersale::getStatus , status);
         }
         query.andEq(LitemallAftersale:: getDeleted, false);
         if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
        	 query.orderBy(sort + " " + order);
         }
         else{
        	 query.orderBy(LitemallAftersale.Column.addTime.desc());
         }
         query.limit(page, limit);
         
         List<LitemallAftersale> list = query.select();
         return list;
			/*
			 * LitemallAftersaleExample example = new LitemallAftersaleExample();
			 * LitemallAftersaleExample.Criteria criteria = example.or(); if (orderId !=
			 * null) { criteria.andOrderIdEqualTo(orderId); } if
			 * (!StringUtils.isEmpty(aftersaleSn)) {
			 * criteria.andAftersaleSnEqualTo(aftersaleSn); } if (status != null) {
			 * criteria.andStatusEqualTo(status); } criteria.andDeletedEqualTo(false); if
			 * (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
			 * example.setOrderByClause(sort + " " + order); } else{
			 * example.setOrderByClause(LitemallAftersale.Column.addTime.desc()); }
			 * 
			 * PageHelper.startPage(page, limit); return
			 * aftersaleMapper.selectByExample(example);
			 */
    }

    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public int countByAftersaleSn(Integer userId, String aftersaleSn) {
    	
    	LitemallAftersale seal = new LitemallAftersale();
    	seal.setDeleted(false);
    	seal.setUserId(userId);
    	seal.setAftersaleSn(aftersaleSn);
    	return (int)aftersaleDao.templateCount(seal);
		/*
		 * LitemallAftersaleExample example = new LitemallAftersaleExample();
		 * example.or().andUserIdEqualTo(userId).andAftersaleSnEqualTo(aftersaleSn).
		 * andDeletedEqualTo(false); return (int)
		 * aftersaleMapper.countByExample(example);
		 */
    }

    // TODO 这里应该产生一个唯一的编号，但是实际上这里仍然存在两个售后编号相同的可能性
    public String generateAftersaleSn(Integer userId) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String now = df.format(LocalDate.now());
        String aftersaleSn = now + getRandomNum(6);
        while (countByAftersaleSn(userId, aftersaleSn) != 0) {
            aftersaleSn = now + getRandomNum(6);
        }
        return aftersaleSn;
    }

    public void add(LitemallAftersale aftersale) {
        aftersale.setAddTime(LocalDateTime.now());
        aftersale.setUpdateTime(LocalDateTime.now());
       aftersaleDao.insertTemplate(aftersale,true);
		/* aftersaleMapper.insertSelective(aftersale); */
    }

    public void deleteByIds(List<Integer> ids) {
         aftersaleDao.getSQLManager().executeUpdate("update litemall_aftersale set deleted = #deleted# , updatetime = #updatetime# "
         		+ "where id in( #join(ids)#)  and deleted = #oldDeleted#", BeetlParams.create().set("deleted", true)
         		.set("updatetime", LocalDateTime.now())
         		.set("ids", ids).set("oldDeleted", false));
			/*
			 * LitemallAftersaleExample example = new LitemallAftersaleExample();
			 * example.or().andIdIn(ids).andDeletedEqualTo(false); LitemallAftersale
			 * aftersale = new LitemallAftersale();
			 * aftersale.setUpdateTime(LocalDateTime.now()); aftersale.setDeleted(true);
			 * aftersaleMapper.updateByExampleSelective(aftersale, example);
			 */
    }

    public void deleteById(Integer id) {
    	LitemallAftersale aftersale = new LitemallAftersale();
   	 	aftersale.setUpdateTime(LocalDateTime.now());
        aftersale.setDeleted(true);
        aftersale.setId(id);
        aftersaleDao.updateTemplateById(aftersale);
        //aftersaleMapper.logicalDeleteByPrimaryKey(id);
    }

    public void deleteByOrderId(Integer userId, Integer orderId) {
    	
    	LitemallAftersale update = new LitemallAftersale();
    	update.setUpdateTime(LocalDateTime.now());
    	update.setDeleted(true);
    	aftersaleDao.createLambdaQuery().andEq(LitemallAftersale::getUserId, userId)
    	.andEq(LitemallAftersale::getOrderId, orderId).updateSelective(update);
    	
		/*
		 * LitemallAftersale aftersale = new LitemallAftersale();
		 * aftersale.setUpdateTime(LocalDateTime.now()); aftersale.setDeleted(true);
		 * aftersale.setId(id); aftersaleDao.updateById(entity)
		 * 
		 * LitemallAftersaleExample example = new LitemallAftersaleExample();
		 * example.or().andOrderIdEqualTo(orderId).andUserIdEqualTo(userId).
		 * andDeletedEqualTo(false); LitemallAftersale aftersale = new
		 * LitemallAftersale(); aftersale.setUpdateTime(LocalDateTime.now());
		 * aftersale.setDeleted(true);
		 * aftersaleMapper.updateByExampleSelective(aftersale, example);
		 */
    }

    public void updateById(LitemallAftersale aftersale) {
        aftersale.setUpdateTime(LocalDateTime.now());
        
        aftersaleDao.updateTemplateById(aftersale);
        
		/* aftersaleMapper.updateByPrimaryKeySelective(aftersale); */
    }

    public LitemallAftersale findByOrderId(Integer userId, Integer orderId) {
    	
    	LitemallAftersale aftersale = new LitemallAftersale();
        aftersale.setUserId(userId);
        aftersale.setOrderId(orderId);
        return aftersaleDao.templateOne(aftersale);
		/*
		 * LitemallAftersaleExample example = new LitemallAftersaleExample();
		 * example.or().andOrderIdEqualTo(orderId).andUserIdEqualTo(userId).
		 * andDeletedEqualTo(false); return aftersaleMapper.selectOneByExample(example);
		 */
    }
}
